﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SQLite;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using BS_2.Class;
using CCWin;

namespace BS_2
{
    public partial class Form_AddData : CCWin.Skin_DevExpress
    {
        private string filecode;
        private string subname;
        private string subcode = "-1";
        public Form_AddData()
        {
            this.ShowInTaskbar = false;
            InitializeComponent();
        }

        private void loadsub()
        {
            subarea.Items.Clear();//左边下拉框清空先
            string sql = "select subname from subgeo where prjcode=" + Globale.project_code ;
            DataTable dt = DataAccess.Get_DataTable(sql, "sub");
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    subarea.Items.Add(dt.Rows[i][0].ToString());//左边下拉框添加项
                }
            }
            //subarea.SelectedIndex = 0;
        }

        private void Form_AddData_Load(object sender, EventArgs e)//次窗体load
        {
            loadsub();//load左边下拉框
            appendtype.SelectedIndex = 0;//附件下拉框类型清空
            skinButton2.Enabled = false;//设置skinbutton2不可操作
        }

        private void Submit_Click(object sender, EventArgs e)//左边submit按钮click事件
        {
            try
            {
                DialogResult dr = MessageBoxEx.Show("确认录入资料吗？", "提示", MessageBoxButtons.OKCancel);
                if (dr == DialogResult.OK)
                {
                    string name = dataname.Text.Trim();
                    string source = datasource.Text.Trim();
                    string sub = subarea.SelectedItem.ToString();
                    string shuoming = datashuoming.Text.Trim();//资料描述
                    string date = DateTime.Now.ToString("yyyy-MM-dd");

                    string sql1 = "select subcode from subgeo where prjcode=" + Globale.project_code + " and subname='" + sub + "'";//通过globale的prjcode找到这里的datacode
                    subcode = DataAccess.Get_Row1_Col1_Value(sql1);//sql执行在subgeo表中找到的第一行第一列的subcode

                    if (name == "" || source == "")
                    {
                        MessageBoxEx.Show("资料名称或资料来源不能为空！", "输入提示");
                        return;
                    }
                    //通过这边的name，projectcode和下拉框里的datacode在geodata表中找到filename
                    string sql = "select dataname from data where dataname='" + name + "'  and subcode='" + subcode + "'";
                    string resultquery = DataAccess.Get_Row1_Col1_Value(sql);//语句执行成功则报错
                    if (resultquery != "")
                    {
                        MessageBoxEx.Show("同一范围内资料名称不能重复，请检查！", "输入提示");
                        return;
                    }


                    //录入信息
                    sql = "insert into data(subcode,dataname,datasource,datadescribe,datadate) values(" + subcode + ",'" + name + "','" + source + "','" + shuoming + "','" + date + "')";
                    int result = DataAccess.Run_SQL(sql);
                    //MessageBox.Show(subcode);
                    if (result == 1)
                    {

                        MessageBoxEx.Show("资料信息录入成功，请上传附件。", "提示");
                        sql = "select datacode from data where dataname='" + name + "'  and subcode='" + subcode + "'";
                        filecode = DataAccess.Get_Row1_Col1_Value(sql);//data代码
                        subname = sub;
                        skinButton2.Enabled = true;
                        skinDataGridView1.Rows.Clear();
                    }
                    else
                    {
                        MessageBoxEx.Show("资料录入失败！", "提示");
                    }
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.ToString());
            }
        }

        private void SkinButton1_Click(object sender, EventArgs e)
        {

            using (OpenFileDialog dialog = new OpenFileDialog())
            {
                dialog.Multiselect = false;
                if (appendtype.SelectedIndex == 0)
                {
                    dialog.Filter = "文档|*.pdf;*.pdf";
                }
                else if (appendtype.SelectedIndex == 1)
                {
                    dialog.Filter = "图片|*.jpg;*.jpg";
                }
                else if (appendtype.SelectedIndex == 2)
                {
                    dialog.Filter = "矢量压缩文件|*.zip;*.zip";
                }
                else if (appendtype.SelectedIndex == 3)
                {
                    dialog.Filter = "三维模型|*.csv;*.csv";
                }
                else if (appendtype.SelectedIndex == 4)
                {
                    dialog.Filter = "栅格数据|*.tif;*.tif";
                }
                else if (appendtype.SelectedIndex == 5)
                {
                    dialog.Filter = "剖面图压缩包|*.zip;*.zip";
                }
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        this.skinTextBox1.Text = dialog.FileName;
                        string lujing = dialog.SafeFileName;
                        /*int length = lujing.Split('\\').Length;
                        string lujing1 = lujing.Split('\\')[length - 1];*/
                        string lujing3 = lujing.Split('.')[0];
                        appendname.Text = lujing3;
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                }
            }
        }//将textbox的内容设定为选中的文件的路径

        private void SkinButton2_Click(object sender, EventArgs e)//进行上传？
        {
            DialogResult dr = MessageBoxEx.Show("确认上传附件吗？", "提示", MessageBoxButtons.OKCancel);
            if (dr == DialogResult.OK)
            {
                string name = appendname.Text;//附件名称(自定义的)
                string type = appendtype.SelectedItem.ToString();//附件类型(自定义的)
                string filetype = Path.GetExtension(this.skinTextBox1.Text).ToLower();//得到该文件的路径的扩展名如.txt

                /*if (appendname1.Text.Trim() == "")
                {
                    MessageBoxEx.Show("附件名称不能为空！", "输入提示");
                    return;
                }*/
                if (this.skinTextBox1.Text == "")
                {
                    MessageBoxEx.Show("请选择文件！", "输入提示");
                    return;
                }
                if (appendtype.SelectedIndex == 0)
                {
                    if (filetype != ".doc" && filetype != ".docx" && filetype != ".pdf")
                    {
                        MessageBoxEx.Show("附件类型不是文档，请修改！", "输入提示");
                        return;
                    }
                }
                if (appendtype.SelectedIndex == 1)
                {
                    if (filetype != ".bmp" && filetype != ".gif" && filetype != ".jpeg" && filetype != ".jpg" && filetype != ".png" && filetype != ".tif" && filetype != ".tiff")
                    {
                        MessageBoxEx.Show("附件类型不是图片，请修改！", "输入提示");
                        return;
                    }
                }
                if (appendtype.SelectedIndex == 2)
                {

                    if (filetype != ".zip" )
                    {
                        MessageBoxEx.Show("附件类型不是矢量数据，请修改！", "输入提示");
                        return;
                    }
                }
                if (appendtype.SelectedIndex == 3)
                {

                    if (filetype != ".csv")
                    {
                        MessageBoxEx.Show("附件类型不是三维数据请修改！", "输入提示");
                        return;
                    }
                }
                if (appendtype.SelectedIndex == 4)
                {

                    if (filetype != ".tif")
                    {
                        MessageBoxEx.Show("附件类型不是栅格数据请修改！", "输入提示");
                        return;
                    }
                }
                if (appendtype.SelectedIndex == 5)
                {

                    if (filetype != ".zip")
                    {
                        MessageBoxEx.Show("附件类型不是剖面图数据请修改！", "输入提示");
                        return;
                    }
                }

                string sql = "select appendname from append where datacode=" + filecode ;
                string resultquery = DataAccess.Get_Row1_Col1_Value(sql);
                if (resultquery == appendname.Text)
                {
                    MessageBoxEx.Show("附件名称不能重复，请检查！", "输入提示");
                    return;
                }
                LoadingHelper.ShowLoadingScreen();
                FileStream fs = new FileStream(this.skinTextBox1.Text, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                BinaryReader br = new BinaryReader(fs);
                Byte[] byData = br.ReadBytes((int)fs.Length);


                //sql = "insert into geodata_file(filecode,prjcode,datacode,appendname,appendtype,appendfile,appendfiletype) values("+filecode+","+ Globale.project_code + "," +subcode + ","+name+","+type + ","+byData+","+filetype + ")";
                /*sql = "insert into data(datatype) values('" + type + "')";
                int i =DataAccess.Run_SQL(sql);
                if (i == 0)
                {
                    MessageBoxEx.Show("类型上传失败", "提示");
                }*/

                //                      子区代码  prjcode  
                sql = "insert into append(datacode,appendname,appendtype,appenddata,append_x,append_y) values(?,?,?,?,?,?)";
                SQLiteParameter[] parameters = {
                    new SQLiteParameter("?datacode",DbType.Int32),
                    //new SQLiteParameter("?prjcode", DbType.Int32),
                    //new SQLiteParameter("?subcode", DbType.String),
                    new SQLiteParameter("?appendname", DbType.String),
                    new SQLiteParameter("?appendtype", DbType.String),
                    new SQLiteParameter("?appenddata", DbType.Binary),
                    new SQLiteParameter("?append_x", DbType.String),
                    new SQLiteParameter("?append_y", DbType.String),
                    /*new SQLiteParameter("?appendfiletype", DbType.String)*/};

                //parameters[0].Value = Globale.project_code;
                //parameters[1].Value = Globale.project_code;
                parameters[0].Value = filecode;
                parameters[1].Value = name;
                parameters[2].Value = type;
                parameters[3].Value = byData;
                parameters[4].Value = appendxBox.Text;
                parameters[5].Value = appendyBox.Text;
                //parameters[6].Value = filetype;

                int result = DataAccess.Run_SQLParameter(sql, parameters);
                LoadingHelper.CloseForm();
                if (result == 1)
                {
                    int index = skinDataGridView1.Rows.Add();
                    skinDataGridView1.Rows[index].Cells[0].Value = name;
                    skinDataGridView1.Rows[index].Cells[1].Value = type;
                    skinDataGridView1.Rows[index].Cells[3].Value = filecode;
                    //skinDataGridView1.Rows[index].Cells[4].Value = filetype;
                    MessageBoxEx.Show("附件上传成功", "提示");
                    this.skinTextBox1.Text = "";
                    appendname1.Text = "";
                }
                else
                {
                    MessageBoxEx.Show("附件上传失败", "提示");
                }
            }
        }

        private void SkinDataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)//已经录入的附件下载
        {
            /*if (e.ColumnIndex == skinDataGridView1.Columns[2].Index)
            {
                if (e.RowIndex < skinDataGridView1.Rows.Count - 1 && e.RowIndex > -1)
                {
                    string filecode = skinDataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
                    string filename = skinDataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
                    string path = "";
                    FolderBrowserDialog fdialog = new FolderBrowserDialog();
                    fdialog.Description = "请选择保存文件夹";
                    if (fdialog.ShowDialog() == DialogResult.OK)
                    {
                        if (String.IsNullOrEmpty(fdialog.SelectedPath))
                        {
                            MessageBoxEx.Show("文件夹不能为空", "提示");
                            return;
                        }
                        path = fdialog.SelectedPath + "\\" + filename + skinDataGridView1.Rows[e.RowIndex].Cells[4].Value.ToString();

                        LoadingHelper.ShowLoadingScreen();
                        string sql = "select appendfile from geodata_file where filecode=" + filecode + " and appendname='" + filename + "'";
                        DataTable db = DataAccess.Get_DataTable(sql, "appendfile");

                        Byte[] Files = (Byte[])db.Rows[0][0];

                        BinaryWriter bw = new BinaryWriter(File.Open(path, FileMode.OpenOrCreate));

                        bw.Write(Files);

                        bw.Close();
                        LoadingHelper.CloseForm();
                        MessageBoxEx.Show("附件已下载", "提示");
                    }
                }
            }*/
        }

        private void appendname_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = true;
        }
    }
}
